<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Factories\HasFactory;


/**
 * 大赛团队表
 */

class CompetiteActivityGroup extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'competite_activity_group';



    /**
     * 根据团队id获取团队名称
     * @param $content
     */
    public function getGroupNameByGroupId($group_id, $field = 'name')
    {
        $res = $this->select($field)->where('id', $group_id)->first();
        if (is_string($field)) {
            return $res[$field];
        }
        return $res;
    }


    /**
     * 判断活动是否允许添加团队
     * @param con_id 活动id
     */
    public function isAllowAddGroup($con_id)
    {
        $res = CompetiteActivity::where('id', $con_id)->where('is_del', 1)->value('deliver_way');
        if (empty($res)) {
            return '此活动不存在';
        }
        if ($res == 2) {
            return '此活动只允许前端用户自己投递作品，不允许添加团队';
        }
        return true;
    }

    /**
     * 获取团队列表
     * @param field int 获取字段信息  数组
     * @param con_id int 活动id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param keywords string 搜索关键词(类型名称)
     */
    public function lists($field, $con_id, $keywords, $start_time, $end_time, $page, $limit)
    {
        if (empty($field)) {
            $field = ['id', 'con_id', 'account', 'name', 'img', 'intro', 'tel', 'contacts', 'create_time'];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->Orwhere('name', 'like', '%' . $keywords . '%')->Orwhere('account', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($con_id,  $start_time, $end_time) {
                if ($con_id) {
                    $query->where('con_id', $con_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        $controllerObj = new Controller();
        $res = $controllerObj->disPageData($res);

        return $res;
    }

    /**
     * 获取团队详情
     * @param con_id int 活动id
     */
    public function detail($id, $field = [])
    {
        if (empty($field)) {
            $field = ['id', 'con_id', 'account', 'name', 'img', 'intro', 'tel', 'contacts', 'create_time'];
        }
        $res = $this->select($field)
            ->where('is_del', 1)
            ->where('id', $id)
            ->first();
        return $res;
    }
}
